const mongoose = require('mongoose');
//let path = require('path');
// let Promise = require('bluebird');
let _ = require('lodash');
//let _ = require('underscore');
let findOrCreate = require('mongoose-findorcreate');
let config=require('../config');
let dbUrl=config.mongodb.uri;

function initDb(dbUrl) {
    let options = {
        server: {
            auto_reconnect: true,
            poolSize: 10
        },
        useNewUrlParser: true
    };
    mongoose.connect(dbUrl, options, (err) => {
        if (!dbUrl) {
            console.log('url地址不存在');
            return;
        }
        //console.log(dbUrl);
        let models = require('node-require-directory')(__dirname);
        Objects.keys(models).map(item=> {
            console.log(item);
            console.log(models[item]);
            mongoose.model(item,models[item]);
        });
        //console.log(models);
        if (err) {
            console.log('Mongoose connection error: ' + err.message)
        } else {
            console.log('数据库连接成功');
        }
    });
    mongoose.connection.on('disconnected', function () {
        console.log('Mongoose connection disconnected')
    });
}

// mongoose.Promise = Promise;
function generateModels(uri) {
    if (!uri) {
        return;
    }
    //console.log(uri);
    let models = require('node-require-directory')(__dirname);

    //let connection = mongoose.createConnection(uri);
    let connection = mongoose.createConnection(uri,{useNewUrlParser: true});
    let result = {};

    Object.keys(models).forEach(function (key) {
        if (key === 'index' || key === 'config') return;
        // add find or create static method
        //console.log(models[key]);
        let schema = models[key]();
        schema.set('timestamps', true);
        schema.plugin(findOrCreate);
        // schema.plugin(timestamps);
        // add virtual path based on Date path
        executeVirtualPath(schema);
        let modelName = capitaliseFirstLetter(key);
        //console.log(modelName);
        result[modelName] = connection.model(modelName, schema);
    });
    //console.log(result);
    return result;
}

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// add virtual path
function addVirtualPath(schema, property) {
    schema.virtual(property + 'Ms').get(function () {
        if (this[property]) {
            return this[property].getTime();
        }
        return undefined;
    });
}

// execute virtual path
function executeVirtualPath(schema) {
    if (!schema || !schema.obj) {
        return;
    }

    // set schema option
    schema.set('toObject', {getters: true, virtuals: true});
    schema.set('toJSON', {getters: true, virtuals: true});

    Object.keys(schema.obj).forEach(function (property) {
        if (schema.obj[property] === Date) {
            addVirtualPath(schema, property);
        } else if (_.isObject(schema.obj[property])) {
            let subObj;
            if (_.isArray(schema.obj[property])) {
                subObj = schema.obj[property][0];
            } else {
                subObj = schema.obj[property];
            }
            // object
            if (subObj.type) {
                // type property exist, is not a sub schema
                if (subObj.type === Date) {
                    // type is Date
                    addVirtualPath(schema, property);
                }
            } else {
                // type property not exist, is a sub schema
                executeVirtualPath(subObj);
            }
        }
    });
}
module.exports =generateModels(dbUrl);
